<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Vue3 登录页</title>
    <script src="https://unpkg.com/vue@3.2.36"></script>

</head>
<body>
<div id="app">
    <div class="login-container">
        <h2>用户登录</h2>
        <form @submit.prevent="handleLogin">
            <div class="form-group">
                <label>用户名：</label>
                <input type="text" v-model="form.username" required>
            </div>
            <div class="form-group">
                <label>密码：</label>
                <input type="password" v-model="form.password" required>
            </div>
            <button type="submit" :disabled="loading">
                {{ loading ? '登录中...' : '立即登录' }}
            </button>
            <div v-if="error" class="error">{{ error }}</div>
        </form>
    </div>
</div>

<script>
    const { createApp, reactive, ref } = Vue;

    createApp({
        setup() {
            // 表单数据
            const form = reactive({
                username: '',
                password: ''
            });

            // 状态管理
            const loading = ref(false);
            const error = ref(null);

            // 登录方法
            const handleLogin = async () => {
                error.value = null;
                loading.value = true;

                try {
                    const response = await fetch('/login', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(form)
                    });

                    if (!response.ok) {
                        throw new Error('登录失败');
                    }

                    const data = await response.json();
                    console.log('登录成功:', data);
                    // 这里处理登录成功后的逻辑，例如跳转页面
                    alert('登录成功！');

                } catch (err) {
                    error.value = err.message || '网络请求失败';
                } finally {
                    loading.value = false;
                }
            };

            return { form, handleLogin, loading, error };
        }
    }).mount('#app');
</script>
</body>
</html>


<style>
    .login-container {
        max-width: 300px;
        margin: 50px auto;
        padding: 20px;
        border: 1px solid #ddd;
        border-radius: 5px;
    }
    .form-group {
        margin-bottom: 15px;
    }
    input {
        width: 100%;
        padding: 8px;
        margin-top: 5px;
    }
    button {
        width: 100%;
        padding: 10px;
        background: #42b983;
        border: none;
        color: white;
        cursor: pointer;
    }
    button:disabled {
        background: #ccc;
    }
    .error {
        color: red;
        margin-top: 10px;
    }
</style>